package com.magicodex.bookkeeping.biz.accounting.util;

import android.content.Context;

import com.magicodex.bookkeeping.biz.accounting.constant.AccountingConstants;
import com.magicodex.bookkeeping.biz.accounting.dto.AccountingDTO;
import com.magicodex.bookkeeping.biz.common.constant.NumberConstants;
import com.magicodex.bookkeeping.biz.common.util.CheckUtil;
import com.magicodex.bookkeeping.biz.common.util.CollectionUtil;
import com.magicodex.bookkeeping.biz.common.util.FileUtil;
import com.magicodex.bookkeeping.ui.accounting.AccountingListViewAdapter;

import java.time.ZonedDateTime;
import java.util.List;

/**
 * @author mh.z
 */
public class AccountingDataUtil {

    /**
     * 处理数据变更
     *
     * @param context
     * @param adapter
     */
    public static void notifyDataSetChanged(Context context, AccountingListViewAdapter adapter) {
        CheckUtil.notNull(context, "context null");
        CheckUtil.notNull(adapter, "adapter null");

        List<AccountingDTO> recordList = adapter.getRecords();
        // 对记录进行排序
        sortAccountingRecords(recordList);
        adapter.setRecords(recordList);

        // 更新列表
        adapter.notifyDataSetChanged();
        // 保存数据
        String json = AccountingJsonUtil.stringifyAccountingDTOs(recordList);
        FileUtil.writeFile(context, AccountingConstants.DATA_PATH, json);
    }

    /**
     * 对记录进行排序
     *
     * @param records
     */
    public static void sortAccountingRecords(List<AccountingDTO> records) {
        if (CollectionUtil.isEmpty(records)) {
            return;
        }

        records.sort((left, right) -> {
            ZonedDateTime leftDate = left.getLastCheckedDate();
            ZonedDateTime rightDate = right.getLastCheckedDate();

            if (leftDate == null && rightDate == null) {
                return NumberConstants.NUMBER_0;
            } else if (leftDate == null) {
                return NumberConstants.NUMBER_1;
            } else if (rightDate == null) {
                return NumberConstants.NUMBER_NEG_1;
            }

            return rightDate.compareTo(leftDate);
        });
    }

}
